<?php

namespace App\Imports;

use App\Http\Controllers\Asset\AssetHelper;
use App\Models\AssetStock;
use Exception;
use Illuminate\Support\Collection;
use Illuminate\Validation\Rule;
use Maatwebsite\Excel\Concerns\OnEachRow;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Row;
use Validator;

class AssetStocksImport implements OnEachRow
{
    use AssetHelper;
    use AssetImportTrait;

    public function __construct()
    {
        // 需要设置local, 否则Validator处理中文会有问题
        setlocale(LC_ALL, "zh_CN.UTF-8");
    }

    /**
     * @param Row $row
     */
    public function onRow(Row $row)
    {
        $rowIndex = $row->getIndex();
        // skip heading row
        if ($rowIndex == 1) {
            return;
        }
        $row = $row->toArray();

        $this->createAsset($row, $rowIndex);
    }

    /**
     * 名称,物品编码,单位/市场价,单位/购入价,初始数量,有效数量,借出数量,总数,主类,副类,品牌,归属,保管人,供应商,仓库
     * @param array $row
     * @param int $rowIndex
     * @throws Exception
     */
    private function createAsset(array $row, int $rowIndex)
    {
        $dateFormat = config('app.date_format');
        $errors = $this->validateAsset($row, $rowIndex, $dateFormat);
        if ($errors->count() > 0) {
            throw new Exception($errors);
        }
        $brandName = $row[10];
        $brand_id = $this->getOrNewBrand($brandName)->id;
        $affiliationName = $row[11];
        $affiliation_id = $this->getOrNewAffiliation($affiliationName)->id;
        $keeperName = $row[12];
        $keeper_id = $this->getOrNewKeeper($keeperName)->id;
        $primaryCategoryId = $this->getPrimaryCategoryByName($row[8])['id'];
        $assetStockData = [
            'name' => $row[0],
            'product_model_number' => $row[1],
            'marking_price_per_unit' => $row[2],
            'bid_price_per_unit' => $row[3],
            'init_quantity' => $row[4],
            'available_quantity' => $row[5] ?? $row[4],
            'checkout_quantity' => $row[6] ?? 0,
            'total_quantity' => $row[7] ?? $row[4],
            'category_id' => $primaryCategoryId,
            'sub_category_id' => $this->getSubCategoryByPrimaryCategoryIdAndName($primaryCategoryId, $row[9])['id'],
            'brand_id' => $brand_id,
            'affiliation_id' => $affiliation_id,
            'keeper_id' => $keeper_id
        ];
        // optional
        // 供应商
        $vendor_id = null;
        $vendorName = $row[13];
        if (!empty($vendorName) && $vendorName != '无') {
            $vendor_id = $this->getOrNewVendor($vendorName)->id;
        }
        if (!empty($vendor_id)) {
            $assetStockData['vendor_id'] = $vendor_id;
        }
        // 仓库
        $locationName = $row[14];
        $location_id = null;
        if (!empty($locationName)) {
            $location_id = $this->getOrNewLocation($locationName)->id;
        }
        if (!empty($location_id)) {
            $assetStockData['location_id'] = $location_id;
        }
        AssetStock::create($assetStockData);
    }

    private function validateAsset(Array $row, $rowIndex, $dateFormat): Collection
    {
        $availablePrimaryCategories = $this->getAllPrimaryCategoryNames() ?? [];
        $v1 = Validator::make($row, [
            '0' => "required", // 名称
            '1' => "nullable", // 物品编码
            '2' => "required", // 单位/市场价
            '3' => "required", // 单位/购入价
            '4' => "required", // 初始数量
            '5' => "nullable", // 有效数量
            '6' => "nullable", // 借出数量
            '7' => "nullable", // 总数
            '8' => ['required', Rule::in($availablePrimaryCategories)], // 主类
            '9' => 'required', // 副类
            '10' => "required", // 品牌
            '11' => "required", // 归属
            '12' => "required", // 保管人
            '13' => "nullable", // 供应商
            '14' => "nullable", // 仓库
        ], [
            '8' => ":attribute【 I$rowIndex 】 :input 非法 请使用如下可选值 【 :values 】",
            'required' => "行: $rowIndex  【 :attribute 】数据是必须的"
        ], [
            '0' => "名称",
            '1' => "物品编码",
            '2' => "单位/市场价",
            '3' => "单位/购入价",
            '4' => "初始数量",
            '5' => "有效数量",
            '6' => "借出数量",
            '7' => "总数",
            '8' => "主类",
            '9' => "副类",
            '10' => "品牌",
            '11' => "归属",
            '12' => "保管人",
            '13' => "供应商",
            '14' => "仓库",

        ])->errors();
        // 检查主副类是否满足关系
        $primaryCategoryName = $row[8] ?? '_undefined_';
        $validSubCategories = $this->getSubCategoriesByPrimaryCategoryName($primaryCategoryName)->pluck("name") ?? [];
        $subCategoryName = $row[9] ?? "_undefined_";
        $v2 = Validator::make([$subCategoryName], [
            "0" => [Rule::in($validSubCategories)]
        ], [
            "0" => "主类 【 I$rowIndex 】 和 副类 【 J$rowIndex 】 关系错误"
        ])->errors();
        return collect($v1)->merge($v2);
    }
}
